<template>
  <div class="bgc-default pad-20">
    <div class="bg-color-white pad-20">
      <!--顶部搜索 -->
      <div class="top-operate mar-t-20">
        <div class="search-item">
          <label>商品搜索：</label>
          <el-select class="select-class" v-model="searchListQuery.searchType" style="width: 120px">
            <el-option label="商品名称" value="title"></el-option>
          </el-select>
          <el-input @keyup.enter.native="handleSearch" v-model="searchListQuery.keyword" placeholder="请输入关键词">
          </el-input>
          <label class="mar-l-20">商品分类：</label>
          <el-cascader v-model="categoryIds" :props="{ checkStrictly: true }" change-on-select placeholder="选择商品分类"
            :options="categoryData" class="special-input" clearable></el-cascader>
<!--          <label class="mar-l-20">商品组：</label>
          <el-select v-model="searchListQuery.goodsGroupId" filterable placeholder="请选择">
            <el-option label="全部" value="-1"></el-option>
            <el-option v-for="item in selGoodsGroupList" :key="item.goodsGroupId" :label="item.goodsGroupName"
              :value="item.goodsGroupId">
            </el-option>
          </el-select> -->
          <el-button-group class="mar-l-20">
            <el-button type="primary" @click="handleSearch">查询</el-button>
            <el-button plain @click="resetSearch">重置</el-button>
          </el-button-group>
        </div>
      </div>
      <!--商品状态 -->
      <div class="tabs-box mar-t-15">
        <el-tabs type="card" v-model="searchListQuery.searchGoodsStatus" @tab-click="goodsStatusClick">
          <el-tab-pane :label="allTotalGoodsNumLabel" name="0"></el-tab-pane>
          <el-tab-pane :label="putShelfTotalGoodsNumLabel" name="1"></el-tab-pane>
          <el-tab-pane :label="soldOutTotalGoodsNumLabel" name="2"></el-tab-pane>
          <el-tab-pane :label="offShelfTotalGoodsNumLabel" name="3"></el-tab-pane>
        </el-tabs>
      </div>


      <!-- 内容列表 -->
      <div class="table-container">
        <!-- @selection-change="handleSelectionChange" -->
        <el-table ref="multipleTable" :data="goodsList" v-loading="listLoading" element-loading-text="加载中"
          style="width: 100%">
          <!--          <el-table-column width="50px" type="selection"></el-table-column> -->
          <el-table-column label="商品名称" fixed="left">
            <template slot-scope="scope">
              <div class="flex v-align-c cursor-p mar-r-30">
                <label><img :src="scope.row.mainImage" class="user-avatar cursor-p"></label>
                <div class="font-14 pad-l-10 v-align-h height-75">
                  <div class="goods-title">
                    <div class="line-2">
                      <el-tag size="mini" v-if="scope.row.skuFlag == 1" type="danger" effect="light">多</el-tag>
                      {{scope.row.title}}
                    </div>
                  </div>
                  <div class="category-style line-2" v-if="scope.row.categoryName">[{{scope.row.categoryName}}]</div>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="门店零售价" prop="sellPrice">
            <template slot-scope="scope">
              <div v-if="editGoodsPriceIdList.indexOf(scope.row.warehouseGoodsId) > -1">
                <el-input-number :precision="2" style="width: 80px;" v-model="scope.row.sellPrice" :min="0"
                  :controls="false">
                </el-input-number>
              </div>
              <div v-if="editGoodsPriceIdList.indexOf(scope.row.warehouseGoodsId) === -1">
                <span v-if="scope.row.sellPrice">￥{{scope.row.sellPrice}}</span>
                <span v-else>----</span>
                <el-button icon="el-icon-edit" type="text" @click="editGoods(1,scope.row.warehouseGoodsId)"></el-button>
              </div>
              <div v-if="editGoodsPriceIdList.indexOf(scope.row.warehouseGoodsId) > -1" style="margin-top: 5px;">
                <el-button size="mini" @click="cancelEditGoods(1,scope.row.warehouseGoodsId)">取消</el-button>
                <el-button type="primary" size="mini" @click="submitEditGoods(1,scope.row)">确定</el-button>
              </div>
            </template>
          </el-table-column>
          <!--          <el-table-column label="门店实际库存" prop="remainStock">
            <template slot-scope="scope">
              <div v-if="editGoodsStockIdList.indexOf(scope.row.warehouseGoodsId) > -1">
                <el-input v-model="scope.row.remainStock" style="width: 80px;" maxlength="3"
                  @keyup.native="scope.row.remainStock = checkInputNum(scope.row.remainStock)"> </el-input>
              </div>
              <div v-if="editGoodsStockIdList.indexOf(scope.row.warehouseGoodsId) === -1">
                <span v-if="scope.row.remainStock">{{scope.row.remainStock}}</span>
                <span v-else>----</span>
                <el-button icon="el-icon-edit" type="text" @click="editGoods(2,scope.row.warehouseGoodsId)"></el-button>
              </div>
              <div v-if="editGoodsStockIdList.indexOf(scope.row.warehouseGoodsId) > -1" style="margin-top: 5px;">
                <el-button size="mini" @click="cancelEditGoods(2,scope.row.warehouseGoodsId)">取消</el-button>
                <el-button type="primary" size="mini" @click="submitEditGoods(2,scope.row)">确定</el-button>
              </div>
            </template>
          </el-table-column> -->
          <el-table-column label="门店库存">
            <template slot-scope="scope">
              <div>总库存： <span v-if="scope.row.remainStock">{{scope.row.stock}}</span>
                <span v-else>0</span>
              </div>
              <div v-if="editGoodsStockIdList.indexOf(scope.row.warehouseGoodsId) > -1">
                可用库存： <el-input v-model="scope.row.remainStock" style="width: 80px;"
                  @keyup.native="scope.row.remainStock = checkInputNumWithPoint(scope.row.remainStock, 0)">
                </el-input>
              </div>
              <div v-if="editGoodsStockIdList.indexOf(scope.row.warehouseGoodsId) === -1">
                可用库存： <span v-if="scope.row.remainStock">{{scope.row.remainStock}}</span>
                <span v-else>0</span>
                <el-button icon="el-icon-edit" type="text" @click="editGoods(2,scope.row.warehouseGoodsId)">
                </el-button>
              </div>
              <div v-if="editGoodsStockIdList.indexOf(scope.row.warehouseGoodsId) > -1" style="margin-top: 5px;">
                <el-button size="mini" @click="cancelEditGoods(2,scope.row.warehouseGoodsId)">取消</el-button>
                <el-button type="primary" size="mini" @click="submitEditGoods(2,scope.row)">确定</el-button>
              </div>
              <div>占用库存： <span v-if="scope.row.stockInUse">{{scope.row.stockInUse}}</span>
                <span v-else>0</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="门店销量" prop="salesNum" />
          <el-table-column width="140px" label="标签" :formatter="goodsTagFormatter" />
          <!--      <el-table-column label="商品组" prop="goodsGroupList" :formatter="goodsGroupNameFormat" /> -->
          <el-table-column label="状态" prop="goodsStatus">
            <template slot-scope="scope">
              <div style="display:inline">
                <el-switch v-model="scope.row.goodsStatus" active-color="#13ce66" inactive-color="#ff4949"
                  @change="submitEditGoods(3,scope.row)" :active-value=1 :inactive-value=0></el-switch>
              </div>
              <div style="display:inline" v-if="scope.row.goodsStatus == 1">已上架</div>
              <div style="display:inline" v-else-if="scope.row.goodsStatus == 0">已下架</div>
              <div style="display:inline" v-if="scope.row.remainStock == 0">(已售罄)</div>
            </template>
          </el-table-column>

        </el-table>
      </div>
      <!-- 列表分页 -->
      <pagination v-show="total>0" :total="total" :page.sync="searchListQuery.currentPage"
        :limit.sync="searchListQuery.size" @pagination="initGoodsList" />
    </div>
  </div>
</template>

<script>
  import {
    pagingStoreWarehouseGoods,
    listCountStoreWarehouseGoodsStatusNum,
    updateWarehouseGoodsSellPrice,
    updateWarehouseGoodsStock,
    updateWarehouseGoodsStatus
  } from '@/api/warehouse/warehouseGoods.js'
  import {
    getSelGoodsGroupList
  } from '@/api/goods/goodsGroup'
  import {
    listGoodsCategory
  } from '@/api/goods/goods'
  import {
    getByEnterpriseId
  } from '@/api/user/enterprise'

  export default {
    props: {
      storeMemberId: {
        type: String,
        default: 0
      }
    },
    components: {

    },
    directives: {

    },
    data() {
      return {
        total: 0,
        multipleSelection: [],
        listLoading: true,
        searchListQuery: {
          enterpriseId: this.getEnterpriseId(),
          memberId: this.getStoreMemberId(),
          currentPage: 1,
          size: 10,
          keyword: '',
          searchType: 'title',
          goodsStatus: '0',
          goodsGroupId: '-1'
        },
        categoryIds: [],
        goodsList: [],
        // 商品的所有分类json
        categoryData: [],
        // 状态标签集合
        allTotalGoodsNumLabel: '全部（0）',
        putShelfTotalGoodsNumLabel: '已上架（0）',
        offShelfTotalGoodsNumLabel: '已下架（0）',
        soldOutTotalGoodsNumLabel: '已售完（0）',
        editGoodsPriceIdList: [],
        editGoodsStockIdList: [],
        selGoodsGroupList: []
      }
    },
    // 初始化页面
    created() {
      this.initEnterpriseConfig()
      this.initGoodsList()
      this.listGoodsCategory()
      this.getSelGoodsGroupList()
    },
    filters: {
      priceFilter(e) {
        return e.toFixed(2)
      }
    },
    mounted() {},
    methods: {
      getStoreMemberId() {
        if (this.storeMemberId !== undefined && this.storeMemberId > 0) {
          return this.storeMemberId
        }
        return this.getMemberId()
      },
      initGoodsList() {
        this.listLoading = true
        var numQuery = {
          enterpriseId: this.getEnterpriseId(),
          memberId: this.getStoreMemberId(),
          goodsGroupId: this.searchListQuery.goodsGroupId
        }
        listCountStoreWarehouseGoodsStatusNum(numQuery).then(response => {
          this.allTotalGoodsNumLabel = '全部（' + response.data.allTotalGoodsNum + '）'
          this.putShelfTotalGoodsNumLabel = '已上架（' + response.data.putShelfTotalGoodsNum + '）'
          this.soldOutTotalGoodsNumLabel = '已售完（' + response.data.soldOutTotalGoodsNum + '）'
          this.offShelfTotalGoodsNumLabel = '已下架（' + response.data.offShelfTotalGoodsNum + '）'
        })
        this.searchListQuery[this.textCol] = this.keyword
        this.searchListQuery['oneCategoryId'] = ''
        this.searchListQuery['twoCategoryId'] = ''
        this.searchListQuery['threeCategoryId'] = ''
        const categoryIds = this.categoryIds

        if (categoryIds.length === 1) {
          this.searchListQuery['oneCategoryId'] = categoryIds[0]
        }
        if (categoryIds.length === 2) {
          this.searchListQuery['twoCategoryId'] = categoryIds[1]
        }
        if (categoryIds.length === 3) {
          this.searchListQuery['threeCategoryId'] = categoryIds[2]
        }
        pagingStoreWarehouseGoods(this.searchListQuery).then(response => {
          this.total = response.data.total
          this.goodsList = response.data.records
          this.listLoading = false
        })
      },
      // 获取类目
      listGoodsCategory() {
        const enterpriseId = this.getEnterpriseId()
        listGoodsCategory(enterpriseId).then(response => {
          this.categoryData = response.data
        })
      },
      // 获取系统参数
      initEnterpriseConfig() {
        const enterpriseId = this.getEnterpriseId()
        getByEnterpriseId(enterpriseId).then((response) => {
          if (response.isError) return
          this.enterpriseConfig = response.data
        })
      },
      handleSearch() {
        this.searchListQuery.currentPage = 1
        this.initGoodsList()
      },
      resetSearch() {
        this.searchListQuery.searchType = 'title'
        this.searchListQuery.keyword = ''
        this.searchListQuery.currentPage = '1'
        this.searchListQuery.goodsGroupId = '-1'
        this.categoryIds = []
        this.initGoodsList()
      },
      // 勾选
      handleSelectionChange(val) {
        this.multipleSelection = val
        if (this.multipleSelection.length === this.goodsList.length) {
          this.allChecked = true
        } else {
          this.allChecked = false
        }
      },
      // 商品状态
      goodsStatusClick() {
        this.handleSearch()
      },
      editGoods(type, warehouseGoodsId) {
        if (type === 1) {
          this.editGoodsPriceIdList.push(warehouseGoodsId)
        }
        if (type === 2) {
          this.editGoodsStockIdList.push(warehouseGoodsId)
        }
      },
      cancelEditGoods(type, warehouseGoodsId) {
        if (type === 1) {
          this.editGoodsPriceIdList.some((item, i) => {
            if (item === warehouseGoodsId) {
              this.editGoodsPriceIdList.splice(i, 1)
              // 在数组的some方法中，如果return true，就会立即终止这个数组的后续循环
              return true
            }
          })
        }
        if (type === 2) {
          this.editGoodsStockIdList.some((item, i) => {
            if (item === warehouseGoodsId) {
              this.editGoodsStockIdList.splice(i, 1)
              // 在数组的some方法中，如果return true，就会立即终止这个数组的后续循环
              return true
            }
          })
        }
      },
      submitEditGoods(type, row) {
        var that = this
        // const goodsName = row.title
        // let editGoodsParams = '零售价'
        // if (type === 2) {
        //   editGoodsParams = '库存'
        // }
        // if (type === 3) {
        //   const goodsStatusTip = row.goodsStatus === 0 ? '下架' : '上架'
        //   editGoodsParams = '上下架状态为【' + goodsStatusTip + '】'
        // }
        // this.$confirm('确认要修改' + goodsName + editGoodsParams + '吗?', '警告', {
        //   confirmButtonText: '确定',
        //   cancelButtonText: '取消',
        //   type: 'warning'
        // }).then(function() {

        // }).catch(function() {
        //   if (type === 3) {
        //     row.goodsStatus = row.goodsStatus === 0 ? 1 : 0
        //   }
        // })
        const params = {}
        params.warehouseGoodsId = row.warehouseGoodsId
        // 更新价格
        if (type === 1) {
          params.sellPrice = row.sellPrice
          updateWarehouseGoodsSellPrice(params).then(response => {
            if (response.isError) return
            that.cancelEditGoods(type, row.warehouseGoodsId)
            that.msgSuccess(response.msg)
          })
        }
        // 更新库存
        if (type === 2) {
          params.stock = row.remainStock
          if (row.stockInUse && row.stockInUse > 0) {
            params.stock = parseInt(params.stock) + parseInt(row.stockInUse)
          }
          updateWarehouseGoodsStock(params).then(response => {
            if (response.isError) return
            row.stock = params.stock
            that.cancelEditGoods(type, row.warehouseGoodsId)
            that.msgSuccess(response.msg)
          })
        }
        // 更新上下架状态
        if (type === 3) {
          params.goodsStatus = row.goodsStatus
          updateWarehouseGoodsStatus(params).then(response => {
            if (response.isError) {
              row.goodsStatus = row.goodsStatus === 0 ? 1 : 0
              return
            }
            that.initGoodsList()
            that.msgSuccess(response.msg)
          })
        }
      },
      goodsGroupNameFormat(row) {
        let goodsGroupName = ''
        if (row.goodsGroupList !== undefined && row.goodsGroupList.length > 0) {
          row.goodsGroupList.forEach(goodsGroup => {
            goodsGroupName = goodsGroupName + goodsGroup.goodsGroupName + '  '
          })
        }
        return goodsGroupName
      },
      getSelGoodsGroupList() {
        const params = {}
        params.enterpriseId = this.getEnterpriseId()
        getSelGoodsGroupList(params).then(response => {
          this.selGoodsGroupList = response.data
        })
      },
      goodsTagFormatter(row) {
        if (row.goodsTagList !== null && row.goodsTagList !== undefined && row.goodsTagList.length > 0) {
          let tagTip = ''
          row.goodsTagList.forEach(goodsTag => {
            if (goodsTag.goodsTagBusType === 1) {
              tagTip = tagTip + goodsTag.goodsTagName + ' | '
            }
          })
          if (tagTip !== '') {
            tagTip = tagTip.substring(0, tagTip.length - 2)
          }
          return tagTip
        }
        return '-'
      }
    }
  }
</script>
<style lang="less" scoped>
  .top-operate {
    margin-bottom: 0;
    height: 85px;
    background-color: #f7f8fa;
    display: flex;
    align-items: center;
    white-space: nowrap;
    flex-wrap: nowrap;
    width: 100%;
    overflow-x: auto;
  }

  .search-item {
    display: flex;
    align-items: center;
    flex-shrink: 0;
    padding: 0 20px;

    label {
      font-weight: unset;
    }

    >div,
    .el-cascader {
      margin-right: 0px;
    }

    .el-input {
      width: 200px;
    }
  }

  .btn-search {
    height: 60px;
    display: flex;
    align-items: center;
  }

  .user-avatar {
    width: 65px;
    height: 65px;
    display: block;
    padding: 1px;
    border: #efefef 1px solid;
  }

  .category-style {
    color: #636669;
  }

  .v-align-h {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    justify-content: space-between;
  }

  .goods-title {
    color: #155bd4;
    line-height: 1.2;
  }

  // 2行文字展示
  .line-2 {
    line-height: 1.4;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    word-break: break-word;
  }
</style>
